import React, { Component } from 'react'
import { Button, Spin, message, Table, Pagination, Modal, Form, Input, Select, InputNumber } from 'antd'

import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import Empty from '@/pages/Dashboard/common/Empty/index'
import { limitDecimals } from '@/Utils/common'
import { USER_INFO } from '@/Utils/CONST'

const { leagueManagement } = address
const { getPeerNum, createPrivateData, deletePrivateData, getPrivateDataList } = leagueManagement
const { Option } = Select

import './PrivateData.less'

export default class PrivateData extends Component {
  constructor(props) {
    super(props)
    this.state = {
      searchValue: '',
      visible: false,
      loading: true,
      total: 0,
      pageNo: 1, // 当前页
      pageSize: 10, // 每页的条数
      list: [],
      minPeerNum: 0,
      maxPeerNum: 1,
    }
    const { id } = this.props.match.params
    this.consortiumId = id
    this.handleRecord = {}
    const userInfo = JSON.parse(localStorage.getItem(USER_INFO) || '{}')
    this.userInfo = userInfo
  }

  componentDidMount() {
    this.getList()
  }

  get columns() {
    const { leagueInfo } = this.props
    const column = leagueInfo.version === '2.2.1' ? [
      {
        title: '组织成员可读',
        dataIndex: 'memberOnlyRead',
        render: (v, record) => v === 1 ? '是' : '否',
      },
      {
        title: '组织成员可写',
        dataIndex: 'memberOnlyWrite',
        render: (v, record) => v === 1 ? '是' : '否',
      },
    ] : [
      {
        title: '是否公开',
        dataIndex: 'memberOnlyRead',
        render: (v, record) => v === 1 ? '是' : '否',
      },
    ]
    return [
      {
        title: '私有集名称',
        dataIndex: 'name',
      },
      { title: '授权组织', dataIndex: 'policy' },
      { title: '最小分发节点数', dataIndex: 'requiredPeerCount' },
      { title: '最多分发节点数', dataIndex: 'maxPeerCount' },
      { title: '数据保存区块数', dataIndex: 'blockToLive' },
      ...column,
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record, index) => (
          <div className="action" id={`popver${index}`} style={{ position: 'relative' }}>
            <span className={`common-operation ${this.userInfo.id === record.creator ? '' : ''}`} onClick={() => this.openUpadte(record)}>更新</span>
            <span className={`common-operation ${this.userInfo.id === record.creator ? '' : ''}`} onClick={() => this.delete(record)}>删除</span>
          </div>
        ),
      },
    ]
  }

  getPeerNum = (orgIds) => {
    request().post(getPeerNum, { orgIds }).then((res = {}) => {
      if (res.status === 200) {
        this.setState({
          minPeerNum: (res.data || 1) - 1,
          maxPeerNum: res.data || 1,
        })
      }
    })
  }

  onOrgChange = (val = []) => {
    if (val.length > 0) {
      this.getPeerNum(val)
    }
  }

  getList = async() => {
    this.setState({
      loading: true,
    })
    let res = await request().get(`${getPrivateDataList.format({ consortiumId: this.consortiumId })}?pageNum=${this.state.pageNo}&pageSize=${this.state.pageSize}&name=${this.state.searchValue || ''}`)
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      this.setState({
        list: res.data.data,
        total: res.data.total,
      })
    }
  }

  openUpadte = (record = {}) => {
    // if (this.userInfo.id !== record.creator) {
    //   return false
    // }
    this.handleRecord = {
      ...record,
      orgIds: record.orgIds || [],
    }
    this.setState({
      visible: true,
      minPeerNum: record.requiredPeerCount || 0,
      maxPeerNum: record.maxPeerCount || 0,
    })
  }

  changeValueFn = (e) => {
    this.setState({
      searchValue: e.target.value,
    })
  }

  search = () => {
    this.setState({
      pageNo: 1,
    }, () => {
      this.getList()
    })
  }

  addData = () => {
    this.handleRecord = {}
    this.setState({
      visible: true,
    })
  }

  onShowSizeChange = (current, pageSize) => {
    let pageNo = this.state.pageNo
    this.setState({
      pageSize,
      pageNo,
    }, () => {
      this.getList()
    })
  }

  changePaginationFn = (pageNumber) => {
    this.setState({
      pageNo: pageNumber,
    }, () => this.getList())
  }

  onOk = () => {
    this.editForm && this.editForm.validateFields().then(async(values) => {
      const { leagueInfo } = this.props
      if (leagueInfo.version === '2.2.1') {
        values.memberOnlyWrite = !!values.memberOnlyWrite
      } else {
        delete values.memberOnlyWrite
      }
      if (this.handleRecord.id) {
        // 修改
        request().put(createPrivateData.format({ consortiumId: this.consortiumId }), {
          ...values,
          id: this.handleRecord.id,
          memberOnlyRead: !!values.memberOnlyRead,
        }).then((res = {}) => {
          if (res.status === 200) {
            message.success('修改成功')
            this.getList()
            this.handleRecord = {}
            this.setState({
              visible: false,
            })
          }
        })
      } else {
        request().post(createPrivateData.format({ consortiumId: this.consortiumId }), {
          ...values,
          memberOnlyRead: !!values.memberOnlyRead,
        }).then((res = {}) => {
          if (res.status === 200) {
            message.success('创建成功')
            this.getList()
            this.handleRecord = {}
            this.setState({
              visible: false,
            })
          }
        })
      }
    })
  }

  delete = (record) => {
    // if (this.userInfo.id !== record.creator) {
    //   return false
    // }
    Modal.confirm({
      content: '确认删除此数据集?',
      onOk: async() => {
        const { status } = await request().delete(
          deletePrivateData.format({ consortiumId: this.consortiumId, policyId: record.id })
        )
        if (status === 200) {
          message.success('删除成功')
          this.getList()
        }
      },
    })
  }

  render() {
    const { searchValue, loading, list, total, visible, maxPeerNum, minPeerNum } = this.state
    const { leagueInfo, allOrgList } = this.props
    return <div className="PrivateData">
      <div className="handle">
        <Button type="primary" onClick={() => this.addData()}>
          新增私有集
        </Button>
        <div className="common-search">
          <input ref={b => { this.input = b }}
            className="search-input"
            placeholder="请输入私有集名"
            type="text"
            onKeyDown={(event) => {
              event.keyCode === 13 && this.search()
            }
            }
            autoComplete="off"
            onChange={this.changeValueFn}
            value={searchValue}
          />
          <div className="search-btn">
            <img src={require('@/images/org/search.svg')} alt="" onClick={() => this.search()} />
          </div>
        </div>
      </div>

      <Spin spinning={loading}>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Table
            columns={this.columns}
            getPopupContainer={node => {
              if (node) {
                return node.parentNode
              }
              return document.body
            }}
            className={list.length ? '' : 'empty-list'}
            dataSource={list}
            rowKey="id"
            pagination={false}
            locale={{
              emptyText: <div />,
            }}
          />
          {
            !list.length &&
            <Empty />
          }
        </div>
        <div className="pagination-box" style={{ marginBottom: '30px' }}>
          {/* 总数*/}
          {
            list.length > 0 &&
            <Pagination
              current={this.state.pageNo}
              pageSize={this.state.pageSize}
              total={total}
              showSizeChanger
              showQuickJumper
              onShowSizeChange={this.onShowSizeChange}
              onChange={this.changePaginationFn} />
          }
        </div>
      </Spin>
      <Modal
        centered
        destroyOnClose
        className={'fileEdit parentClass'}
        getContainer={() => document.querySelector('.PrivateData')}
        wrapClassName={`fileEdit`}
        title={`${this.handleRecord.id ? '修改' : '新建'}私有集`}
        onCancel={() => this.setState({ visible: false })}
        visible={visible}
        onOk={this.onOk}
      >
        <Form
          ref={ref => { this.editForm = ref }}
          {...{
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
          }}
          colon={false}
        >
          <Form.Item
            label="私有集名称："
            name="name"
            initialValue={this.handleRecord.name || ''}
            rules={[
              { required: true, message: '请输入私有集名称' },
            ]}>
            <Input style={{ width: '100%' }} placeholder="请输入私有集名称" />
          </Form.Item>
          <Form.Item
            label="授权组织："
            name="orgIds"
            initialValue={this.handleRecord.orgIds || []}
            rules={[
              { required: true, message: '请选择授权组织' },
            ]}>
            <Select
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="请选择授权组织"
              onChange={this.onOrgChange}
            >
              {
                allOrgList.map(v => {
                  return <Option key={v.id} value={v.id}>{v.name}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item
            label="最小分发节点数："
            name="minPeerNum"
            initialValue={this.handleRecord.requiredPeerCount || 0}
            rules={[
              {
                required: true, message: '请输入最小分发节点数',
              },
            ]}>
            <InputNumber style={{ width: '180px' }} formatter={limitDecimals(0)}
              parser={limitDecimals(0)} min={0} max={Math.max(0, minPeerNum)} />
          </Form.Item>
          <Form.Item
            label="最大分发节点数："
            name="maxPeerNum"
            initialValue={this.handleRecord.maxPeerCount || 1}
            rules={[
              { required: true, message: '请输入最大分发节点数' },
            ]}>
            <InputNumber style={{ width: '180px' }} formatter={limitDecimals(0)}
              parser={limitDecimals(0)} min={1} max={Math.max(1, maxPeerNum)} />
          </Form.Item>
          <Form.Item
            label="数据保存区块数："
            name="blockNum"
            initialValue={this.handleRecord.blockToLive || 0}
            help="输入大于等于0的整数。若为0则代表一直保存私有数据"
            rules={[
              { required: true, message: '请输入数据保存区块数' },
            ]}>
            <InputNumber style={{ width: '180px' }} formatter={limitDecimals(0)}
              parser={limitDecimals(0)} min={0} />
          </Form.Item>
          <Form.Item
            label={ leagueInfo.version === '2.2.1' ? '组织成员可读：' : '是否公开：'}
            name="memberOnlyRead"
            initialValue={this.handleRecord.memberOnlyRead === 0 ? 0 : this.handleRecord.memberOnlyRead || 1}
            rules={[
              { required: true, message: `请选择${leagueInfo.version === '2.2.1' ? '组织成员可读：' : '是否公开：'}` },
            ]}
          >
            <Select
              style={{ width: '180px' }}
            >
              <Option value={1}>是</Option>
              <Option value={0}>否</Option>
            </Select>
          </Form.Item>
          {
            leagueInfo.version === '2.2.1' &&
            <Form.Item
              label={'组织成员可写：'}
              name="memberOnlyWrite"
              initialValue={this.handleRecord.memberOnlyWrite === 0 ? 0 : this.handleRecord.memberOnlyWrite || 1}
              rules={[
                { required: true, message: '请选择组织成员可写' },
              ]}
            >
              <Select
                style={{ width: '180px' }}
              >
                <Option value={1}>是</Option>
                <Option value={0}>否</Option>
              </Select>
            </Form.Item>
          }

        </Form>
      </Modal>
    </div>
  }
}
